import random

from django import forms
from django.shortcuts import render, HttpResponse
from utils.tencent import sms
from projectmanager import settings
from shadow import models
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from django_redis import get_redis_connection


# Create your views here.
def send_sms(request):
    tpl = request.GET.get('type')
    template_id = settings.TENCENT_SMS_APP_TPL.get(tpl)
    if not template_id:
        return HttpResponse('参数错误')
    code = random.randrange(1000, 9999)
    response = sms.send_sms(template_id, value=str(code), receivers=['+8613020868780'])
    try:
        status = response['SendStatusSet'][0]['Code']
        msg = response['SendStatusSet'][0]['Message']
    except KeyError:
        return HttpResponse('send error')
    except IndexError:
        return HttpResponse('send error')
    except TypeError:
        return HttpResponse('send error')
    else:
        if status == 'OK':
            return HttpResponse('send success')
        else:
            return HttpResponse('send failed' + msg)


class RegisterForm(forms.ModelForm):
    mobile_phone = forms.CharField(label='手机号', validators=[RegexValidator(r'', '手机号格式错误'), ])
    password = forms.CharField(label='密码', widget=forms.PasswordInput())

    confirm_password = forms.CharField(label='重复密码', widget=forms.PasswordInput())
    code = forms.CharField(label="验证码")

    # 如果不重写init方法，想要给每个字段增加样式或者其他属性，拿code这个field举例：
    # code = forms.CharField(label='验证码', widget=forms.TextInput(attrs='', placehold=''))

    class Meta:
        model = models.UserInfo
        # fields = "__all__"  # 先按照models里面属性的顺序从上到下排列表单 如果想改变表单的顺序使用可以使用列表传递
        fields = ['username', 'email', 'password', 'confirm_password', 'mobile_phone', 'code']

    def __init__(self, *args, **kwargs):
        """
        重写ModelForm的__init__方法 ，给form添加样式
        :param args:
        :param kwargs:
        """
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = f'请输入{field.label}'


def register(request):
    """
    注册思路：
        1. 点击获取验证码
            1.1 获取手机号
            1.2 发送ajax请求，传递手机号和发送手机号的类型，type=register
            1.3 给手机发送验证码
            1.4 验证码时效处理60s
                手机号:验证码写到redis，并设置过期时间

        2. 触发注册按钮


    :param request:
    :return:
    """
    if request.method == 'GET':
        register_form = RegisterForm()
        return render(request, 'register.html', {'register_form': register_form})


def set_redis(request):
    conn = get_redis_connection('default')
    conn.set('k1', 'v1', ex=20)
    return HttpResponse('set_ok')


def get_redis(request):
    conn = get_redis_connection('default')
    val = conn.get('k1')
    print(val)
    return HttpResponse('get_ok')
